import json
import base64
from Crypto.Cipher import AES
from flask import current_app

def decrypt_phone_number(session_key, encrypted_data, iv):
    """解密微信加密的手机号数据"""
    try:
        session_key = base64.b64decode(session_key)
        encrypted_data = base64.b64decode(encrypted_data)
        iv = base64.b64decode(iv)

        cipher = AES.new(session_key, AES.MODE_CBC, iv)
        decrypted = cipher.decrypt(encrypted_data)
        decrypted = _unpad(decrypted)
        decrypted = json.loads(decrypted.decode('utf-8'))

        # 验证 appid 是否匹配
        if decrypted.get('watermark', {}).get('appid') != current_app.config['WECHAT_APPID']:
            raise Exception('Invalid appid in decrypted data')

        return decrypted

    except Exception as e:
        current_app.logger.error(f"解密手机号异常: {str(e)}")
        return None

def _unpad(s):
    """去除 PKCS#7 填充"""
    return s[:-s[-1]]